package com.gooseeker.business.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.gooseeker.business.PipelineService;
import com.gooseeker.dao.MonitorDao;
import com.gooseeker.dao.PipelineDao;
import com.gooseeker.dao.StationDao;
import com.gooseeker.dao.beans.Monitor;
import com.gooseeker.dao.beans.Overview;
import com.gooseeker.dao.beans.Pipeline;
import com.gooseeker.dao.beans.Station;
import com.gooseeker.dao.beans.Summary;
import com.gooseeker.util.DBSeekerException;

public class PipelineServiceImpl implements PipelineService {
	private MonitorDao monitorDao;
	private PipelineDao pipelineDao;
	private StationDao stationDao;
	
	private int minutes = 1;
	
	public void setMinutes(int minutes) {
		this.minutes = minutes;
	}


	@Autowired
	public void setStationDao(StationDao stationDao) {
		this.stationDao = stationDao;
	}


	@Autowired
	public void setPipelineDao(PipelineDao pipelineDao) {
		this.pipelineDao = pipelineDao;
	}


	@Autowired
	public void setMonitorDao(MonitorDao monitorDao) {
		this.monitorDao = monitorDao;
	}


	@Override
	public List<Summary> queryPipelineSummary() {
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String startTime = sdf1.format(new Date());
		
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 24:00:00");
		String endTime = sdf2.format(new Date());
		
		List<Monitor> monitors = monitorDao.queryMonitorSummary(startTime, endTime);
		List<Summary> summaries = new ArrayList<Summary>();
		
		Map<Long, Summary> tempMap = new HashMap<Long, Summary>();
		for(Monitor m : monitors)
		{
			Summary summary = tempMap.get(m.getPipelineId());
			if(null == summary)
			{
				summary = new Summary();
				summary.setPipelineId(m.getPipelineId());
				summary.setPipelineName(m.getPipelineName());
				tempMap.put(m.getPipelineId(),summary);
			}
			
			List<Overview> overviews = summary.getOverviews();
			if(null == overviews)
			{
				overviews = new ArrayList<Overview>();
				summary.setOverviews(overviews);
			}
			overviews.add(new Overview(m.getResult(),m.getDurations()));
			
		}
		
		Iterator<Summary> it = tempMap.values().iterator();
		while(it.hasNext())
		{
			Summary summary = it.next();
			List<Monitor> mList = monitorDao.queryMonitor4Pipeline(summary.getPipelineId(), startTime, endTime);
			summary.setMonitors(mList);
			summaries.add(summary);
		}
		return summaries;
	}


	@Override
	public List<Pipeline> findPipelines4Page(String keyword, int start, int length) {
		return pipelineDao.findPipelines4Page(keyword, start, length);
	}


	@Override
	public int findPipelines4PageCount(String keyword) {
		return pipelineDao.findPipelines4PageCount(keyword);
	}


	@Override
	public int deletePipeline(long id) {
		return pipelineDao.deletePipeline(id);
	}


	@Override
	public Pipeline getPipeline(long id) {
		return pipelineDao.getPipelineById(id);
	}


	@Override
	public int updatePipeline(long id, String name, String number,int stations, String desc) {
		return pipelineDao.updatePipeline(id, name, number,stations, desc);
	}


	@Override
	public long insertPipeline(String name, String number, String desc) 
	{
		try 
		{
			return pipelineDao.insertPipeline(name, number, desc);
		} catch (DBSeekerException e) {
			throw e;
		}
		
	}
	
	@Override
	public List<Pipeline> getAllPipelines()
	{
	    return pipelineDao.getAllPipelines(null);
	}


	@Override
	public List<Summary> queryPipelineSummary4Day() {

		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		String startTime = sdf1.format(new Date());
		
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 24:00:00");
		String endTime = sdf2.format(new Date());
		
		List<Monitor> monitors = monitorDao.queryMonitorSummary(startTime, endTime);
		List<Summary> summaries = new ArrayList<Summary>();
		
		Map<Long, Summary> tempMap = new HashMap<Long, Summary>();
		for(Monitor m : monitors)
		{
			Summary summary = tempMap.get(m.getPipelineId());
			if(null == summary)
			{
				summary = new Summary();
			}
			
			summary.setPipelineId(m.getPipelineId());
			summary.setPipelineName(m.getPipelineName());
			if(m.getResult() == -1)
			{
				summary.setAlarms(m.getDurations());
			}
			else if(m.getResult() == 0)
			{
				summary.setUnuseds(m.getDurations());
			}
			else
			{
				summary.setNormals(m.getDurations());
			}
			
			tempMap.put(m.getPipelineId(),summary);
		}
		
		Iterator<Summary> it = tempMap.values().iterator();
		while(it.hasNext())
		{
			summaries.add(it.next());
		}
		
		return summaries;
	
	}
	
	@Override
	public List<Summary> queryPipelineSummary4Minutes() {
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
		Calendar calendar = Calendar.getInstance();
		String endTime = sdf1.format(calendar.getTime());
		calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE)-this.minutes);
		//当前时间往前一分钟的 
		String startTime = sdf1.format(calendar.getTime());
		
		Map<Long, Summary> tempMap = new HashMap<Long, Summary>();
		
		List<Pipeline> pipelines = pipelineDao.getAllPipelines(null);
		for(Pipeline p : pipelines)
		{
			tempMap.put(p.getId(), new Summary(p.getId(),p.getName(),p.getNumber(),p.getStations()));
		}
		
		List<Monitor> monitors = monitorDao.queryMonitorSummary(startTime, endTime);
		List<Summary> summaries = new ArrayList<Summary>();
		
		
		for(Monitor m : monitors)
		{
			Summary summary = tempMap.get(m.getPipelineId());
			if(null == summary)
			{
				continue;
			}
			
			if(m.getResult() == -1)
			{
				summary.setAlarms(m.getTotals());
			}
			else if(m.getResult() == 1)
			{
				summary.setNormals(m.getTotals());
			}
			
			tempMap.put(m.getPipelineId(),summary);
		}
		
		Iterator<Summary> it = tempMap.values().iterator();
		while(it.hasNext())
		{
			summaries.add(it.next());
		}
		
//		for(Summary s : summaries)
//		{
//			System.out.println(startTime+"   "+s.getPipelineId() + " : "+s.getAlarms()+ " "+s.getNormals());
//		}
		return summaries;
	
	}


	@Override
	public Map<String, List<Station>> getStationStatus(String pipelineId,String keyword) {
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MINUTE,calendar.get(Calendar.MINUTE)-this.minutes);
		//当前时间往前一分钟的 
		String startTime = sdf1.format(calendar.getTime());
		
		Map<String, List<Station>> stationMap = new HashMap<String, List<Station>>();
		List<Pipeline> pipelines = pipelineDao.getAllPipelines(pipelineId);
        List<Station> allStations = stationDao.getStations4Minutes(startTime);
        for(Pipeline pipeline : pipelines)
        {
        	String key = String.valueOf(pipeline.getId());
        	stationMap.put(key, new ArrayList<Station>());
        }
        
        for (Station station : allStations)
        {
        	String key = String.valueOf(station.getPipelineId());
            List<Station> stations = stationMap.get(key);
            if (null == stations)
            {
//                stations = new ArrayList<Station>();
//                stationMap.put(key, stations);
            	continue;
            }
//            Calendar calendar = Calendar.getInstance(Locale.CHINESE);
//            calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - this.minutes);
//            calendar.set(Calendar.SECOND, 0);
//            calendar.set(Calendar.MILLISECOND, 0);
//            if(station.getCreateTime().before(calendar.getTime()))
//            {
//            	station.setState(0);
//            }
            
//            if(station.getCreateTime().getTime() < calendar.getTime().getTime())
//            {
//            	station.setState(0);
//            }
            stations.add(station);
        }
//        Iterator<String> iterator = stationMap.keySet().iterator();
//        while(iterator.hasNext())
//        {
//        	String key = iterator.next();
//        	System.out.print(startTime+"    "+key+" : ");
//        	List<Station> stations = stationMap.get(key);
//        	for(Station s : stations)
//        	{
//        		System.out.print(s.getState()+" ");
//        	}
//        	System.out.println();
//        }
        
        return stationMap;
	}
	
	public static void main(String[] args)
	{
		 Calendar calendar = Calendar.getInstance(Locale.CHINESE);
         calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - 1);
         calendar.set(Calendar.SECOND, 0);
         
         System.out.println(calendar.getTimeInMillis()<calendar.getTimeInMillis());
	}
}
